package edu.ucsd.cs110.mycity;

import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import edu.ucsd.cs110.mycity.controller.ChatController;
import edu.ucsd.cs110.mycity.controller.ViewController;
import edu.ucsd.cs110.mycity.controller.XMPPController;

public class ChatActivity extends Activity {

	private String toUser;
	private Handler mHandler = new Handler();
	private EditText textMessage;
	private ListView listview;
	private TextView toChatWith;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_chat);
	    textMessage = (EditText) this.findViewById(R.id.chatET);
	    listview = (ListView) this.findViewById(R.id.listMessages);
	    toChatWith = (TextView) this.findViewById(R.id.toChatWith);
	    Intent intent = getIntent();
	    this.toUser = intent.getStringExtra("to");
	    System.out.println("Creating chat room with: " + toUser);
    	toChatWith.setText(toUser);
	    setListAdapter();
		PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
	      XMPPController.getConnection().addPacketListener(new PacketListener() {
	        @Override
	        public void processPacket(Packet packet) {
	          Message message = (Message) packet;
	          if (StringUtils.parseBareAddress(message.getFrom()).equals(toUser)) {
	        	String fromName = StringUtils.parseBareAddress(message.getFrom());
	            // Add the incoming message to the list view
	            mHandler.post(new Runnable() {
	              public void run() {
	                setListAdapter();
	              }
	            });
	          }
	        }
	      }, filter);
	      //
	      Button send = (Button) this.findViewById(R.id.sendBtn);;
	      send.setOnClickListener(new View.OnClickListener() {
	          public void onClick(View view) {
	            String text = textMessage.getText().toString();          
	            Message msg = new Message(toUser, Message.Type.chat);  
	            msg.setBody(text);
	            if (XMPPController.getConnection() != null) {
	            	XMPPController.getConnection().sendPacket(msg);
	              ChatController.addToLog(toUser, StringUtils.parseBareAddress(XMPPController.getConnection().getUser())+":"+text);
	              setListAdapter();
	              textMessage.setText("");
	            }
	          }
	        });
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_chat, menu);
		return true;
	}
	
	private void setListAdapter() {
	    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.listitem, ChatController.get(toUser));
	    listview.setAdapter(adapter);
	  }

	@Override
	protected void onResume() {
		MyCity.resume();
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		MyCity.pause();
		super.onPause();
	}
	
	@Override
	public void onBackPressed() {
		Intent i = new Intent(this,MyCityMapActivity.class);
		i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		this.startActivity(i);
		super.onBackPressed();
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.buddy_list) {
			Intent buddyListIntent = new Intent(ChatActivity.this,BuddyListActivity.class);
			buddyListIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
			this.startActivity(buddyListIntent);
			return true;
		}
		if (item.getItemId() == R.id.map) {
			Intent mapIntent = new Intent(ChatActivity.this,MyCityMapActivity.class);
			mapIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
			this.startActivity(mapIntent);
			return true;
		}
		Log.e("Menu","menu didn't work");
		return super.onOptionsItemSelected(item);
	}
}
